import { defineStore } from 'pinia';
export const useCartStore = defineStore('cart', {
  state: () => ({
    items: JSON.parse(localStorage.getItem('cartItems')) || [],
    selectedItems: [],
  }),
  actions: {
    addToCart(product) {
      const existingItem = this.items.find((item) => item.id === product.id);
      if (existingItem) {
        existingItem.quantity++;
      } else {
        this.items.push({ ...product, quantity: 1, selected: true }); // 默认选中
      }
      this.updateSelectedItems();
      this.saveToLocalStorage();
    },
    removeFromCart(productId) {
      const index = this.items.findIndex((item) => item.id === productId);
      if (index !== -1) {
        this.items.splice(index, 1);
        this.saveToLocalStorage();
      }
    },
    clearCart() {
      this.items = [];
      this.selectedItems = [];
      this.saveToLocalStorage();
    },
    updateCartItemQuantity(productId, quantity) {
      const item = this.items.find(item => item.id === productId);
      if (item) {
        item.quantity = quantity;
        this.saveToLocalStorage();
      }
    },
    getCartItemQuantity(productId) {
      const item = this.items.find(item => item.id === productId);
      return item ? item.quantity : 0;
    },
    saveToLocalStorage() {
      localStorage.setItem('cartItems', JSON.stringify(this.items));
    },
    toggleItemSelection(productId) {
      const item = this.items.find(item => item.id === productId);
      if (item) {
        item.selected = !item.selected;
        this.updateSelectedItems();
        this.saveToLocalStorage();
      }
    },
    updateSelectedItems() {
      this.selectedItems = this.items.filter(item => item.selected);
    },
    clearSelectedItems() {
      this.items = this.items.filter(item => !item.selected);
      this.selectedItems = [];
      this.saveToLocalStorage();
    },
    toggleAllSelection() {
      const allSelected = this.items.every(item => item.selected);
      this.items.forEach(item => {
        item.selected = !allSelected;
      });
      this.updateSelectedItems();
      this.saveToLocalStorage();
    },
    // 在初始化或从本地存储加载数据后调用此方法
    initializeSelection() {
      this.items.forEach(item => {
        if (item.selected === undefined) {
          item.selected = true;
        }
      });
      this.updateSelectedItems();
      this.saveToLocalStorage();
    },
  },
  getters: {
    totalItems: (state) => state.items.reduce((total, item) => total + item.quantity, 0),
    totalPrice: (state) =>
      state.items.reduce((total, item) => total + item.price * item.quantity, 0),
    selectedTotalPrice: (state) => state.selectedItems.reduce((total, item) => total + item.price * item.quantity, 0),
  },
});
